//
//  XSHomeViewController.swift
//  微博项目
//
//  Created by XISHAN on 16/3/2.
//  Copyright © 2016年 XISHAN. All rights reserved.
//

import UIKit



class XSHomeViewController: XSVistorViewController {

    let XSCellID = "XSCellID"
    
    var statusArray:[XSStatus]?
    
    var statusListViewModel:XSStatusListViewModel = XSStatusListViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        if !isLogin{
            vistorView.setPageInformation(nil, infor: nil)
            return
        }
        
        setupUI()
        setupTableView()
        loadData()
        
        
    }
    
    @objc private func loadData(){
        
//        let url = "https://api.weibo.com/2/statuses/friends_timeline.json"
//        
//        let parameters = [ "access_token" : XSUserAccountViewModel.sharedAccountViewModel.accessToken!]
//        
//        XSNetworkTools.sharedXSNeworkTool.request(.GET, urlString: url, parameters: parameters) { (responseObjc, error) -> () in
//            if error != nil{
//                print("主页信息获取错误:\(error)")
//                return
//            }
//            print("获取当前登录用户及其所关注（授权）用户的最新微博:\(responseObjc)")
//            
//            //获取用户及其关注用户的微博数据 进行字典转模型
//            let dicts = responseObjc!["statuses"] as! [[String : AnyObject]]
//            
//            var tempArray = [XSStatus]()
//            for dict in dicts{
//                let status = XSStatus.init(dict: dict)
//                tempArray.append(status)
//            }
//            
//            self.statusArray = tempArray
        statusListViewModel.loadData(pullUpView.isAnimating()) { (isSuccess) -> () in
            if isSuccess{
                self.tableView.reloadData()
                print("首页数据刷新成功")
            
            }else{
                print("首页数据刷新成功")
            }
        }
        
        endRefresh()
    }
    private func setupUI(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", target: nil, action:nil)
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: "pop")
        
    }
    
    private func setupTableView(){
        
        tableView.registerClass(XSStatusCell.self, forCellReuseIdentifier: XSCellID)
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 300
        
        //隐藏分割线
        tableView.separatorStyle = .None
        tableView.backgroundColor = UIColor(white: 239/255, alpha: 1)

        
        tableView.tableFooterView = pullUpView
        
    }
    func pop(){
        
        let vc = XSTempViewController()
        navigationController?.pushViewController(vc, animated: true)
    }

    private func endRefresh(){
        
        pullUpView.stopAnimating()
    }
    //懒加载 下拉加载更多信息控件
    private lazy var pullUpView:UIActivityIndicatorView = {
        
        let indicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        indicatorView.backgroundColor = UIColor.greenColor()
        return indicatorView
        
    }()
}

extension XSHomeViewController{
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return  statusListViewModel.statusArray?.count ?? 0
        
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier(XSCellID, forIndexPath: indexPath) as! XSStatusCell
        
        //cell.textLabel?.text = self.statusArray![indexPath.row].text
        
        cell.statusViewModel = statusListViewModel.statusArray![indexPath.row]
        
        return cell
    }

    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if indexPath.row == self.statusListViewModel.statusArray!.count - 1 && pullUpView.isAnimating() == false {
            self.pullUpView.startAnimating()
            
            print("下来加载更多数据")
            
            self.loadData()
        }
    }
    
}
